/*****************************************************************
 * Copyright 2013 by Long Nguyen (LongNguyen@obuut.com)
 * 
 * Licensed under the Obuut Technologies Co.,ltd; you may not use this file
 * except in compliance with the License. You may obtain a copy of the License
 * at
 * 
 * http://www.obuut.com/licenses
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *****************************************************************/
package com.nullpointer.xchat.task;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;

import com.nullpointer.xchat.utils.KiraGameLog;
import com.nullpointer.xchat.utils.Utils;

public class DefaultGetTask extends AsyncTask<Void, Void, String> {
	private onGetTaskListener listener;
	private String url;

	public DefaultGetTask(String url) {
		super();
		this.url = url;
	}

	@Override
	protected void onPreExecute() {
		if (listener != null) {
			listener.onPreExecute();
		}
	}

	protected String doInBackground(Void... params) {
		try {
			HttpGet get = new HttpGet(url);
	
			KiraGameLog.d("DefaultGetTask URL: " + url);
	
			HttpClient client = Utils.getClient();
	
			get.addHeader("Accept", "application/json; charset=utf-8");
	
			HttpResponse response = client.execute(get);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK
					|| statusCode == HttpStatus.SC_CREATED) {
				return EntityUtils.toString(response.getEntity());
			}	
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void onPostExecute(String content) {

		if (content != null) {
			if (listener != null) {
				listener.onCompleted(content);
			}
		} else {
			getErrorListener("Can't connect to server!");
		}
	}

	public void getErrorListener(String error) {
		if (listener != null) {
			listener.onFailed(error);
		}
	}

	/**
	 * calling this event when task execute
	 * @param listener
	 */
	public void setOnGetTaskListener(onGetTaskListener listener) {
		this.listener = listener;
	}

	public interface onGetTaskListener {
		
		/**
		 * call this function before execute task
		 */
		public void onPreExecute();

		/**
		 * call this function when task execute complete
		 */
		public void onCompleted(String result);
		
		/**
		 * call this function when task execute fail
		 */
		public void onFailed(String error);
	}

}
